#include "stdinclude.h"
#include "utils/string.h"



String StringTools::format_arg_list(const char *fmt, va_list args)
{   	
	if (!fmt) return "";    
	int result = -1, 
		length = 256;    
	char *buffer = 0;    

	while (result == -1 && length<_1MB)    
	{        
		if (buffer) delete [] buffer;        
		buffer = new char [length + 1];     
		memset(buffer, 0, length + 1);      
		#if _WIN32
			// need to use non-CRT thread safe function under Win32
			HRESULT hr = StringCchVPrintfA(buffer, length, fmt, args);
			if ( SUCCEEDED(hr)) 
			{
				result=0;
			}

		#else
			result = _vsnprintf(buffer, length, fmt, args);        
		#endif

		length *= 2;    
	}   
	std::string s(buffer);    

	delete [] buffer;    
	return s;
}




String __cdecl StringTools::format(const char *fmt, ...)
{   
	va_list args;    
	va_start(args, fmt);    
	String s = StringTools::format_arg_list(fmt, args);    
	va_end(args);    
	return s;
}



// trim from start
String & StringTools::ltrim(String &s) 
{
		s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
		return s;
}

// trim from end
String & StringTools::rtrim(String &s) 
{
		s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
		return s;
}


